<template>
  <div class="score-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>成绩管理</span>
        <el-button type="primary" @click="handleAdd" v-if="['admin', 'teacher'].includes(userStore.userInfo?.roleCode || '')">
          <el-icon><Plus /></el-icon>
          录入成绩
        </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="学生搜索">
          <el-input
            v-model="queryForm.studentKeyword"
            placeholder="学号/姓名"
            clearable
            style="width: 180px"
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学期">
          <el-select
            v-model="queryForm.semester"
            placeholder="请选择学期"
            clearable
            style="width: 180px"
            @clear="handleQuery"
          >
            <el-option label="2024-2025第一学期" value="2024-2025第一学期" />
            <el-option label="2024-2025第二学期" value="2024-2025第二学期" />
            <el-option label="2023-2024第一学期" value="2023-2024第一学期" />
            <el-option label="2023-2024第二学期" value="2023-2024第二学期" />
            <el-option label="2022-2023第一学期" value="2022-2023第一学期" />
            <el-option label="2022-2023第二学期" value="2022-2023第二学期" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input
            v-model="queryForm.courseName"
            placeholder="请输入课程名称"
            clearable
            style="width: 180px"
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="courseName" label="课程名称" min-width="150" />
        <el-table-column prop="semester" label="学期" width="150" align="center" />
        <el-table-column prop="score" label="成绩" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getScoreType(row.score)">{{ row.score }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="100" align="center" />
        <el-table-column prop="createTime" label="录入时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right" v-if="['admin', 'teacher'].includes(userStore.userInfo?.roleCode || '')">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.current"
          v-model:page-size="queryForm.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择学生" prop="studentId">
              <el-select
                v-model="form.studentId"
                placeholder="请选择学生"
                filterable
                style="width: 100%"
                :disabled="!!form.id"
              >
                <el-option
                  v-for="student in studentList"
                  :key="student.id"
                  :label="`${student.studentNo} - ${student.realName}`"
                  :value="student.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input 
                v-model="form.courseName" 
                placeholder="如：高等数学"
                clearable
              >
                <template #prefix>
                  <el-icon><Reading /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学期" prop="semester">
              <el-select
                v-model="form.semester"
                placeholder="请选择学期"
                style="width: 100%"
              >
                <el-option label="2024-2025第一学期" value="2024-2025第一学期" />
                <el-option label="2024-2025第二学期" value="2024-2025第二学期" />
                <el-option label="2023-2024第一学期" value="2023-2024第一学期" />
                <el-option label="2023-2024第二学期" value="2023-2024第二学期" />
                <el-option label="2022-2023第一学期" value="2022-2023第一学期" />
                <el-option label="2022-2023第二学期" value="2022-2023第二学期" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成绩" prop="score">
              <el-input-number 
                v-model="form.score" 
                :min="0" 
                :max="100" 
                :precision="1" 
                style="width: 100%"
                controls-position="right"
              />
              <div class="form-tip">0-100分，支持小数</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学分" prop="credit">
              <el-input-number 
                v-model="form.credit" 
                :min="0" 
                :max="10" 
                :precision="1" 
                style="width: 100%"
                controls-position="right"
              />
              <div class="form-tip">0-10学分，支持小数</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" size="large">
            <el-icon><Check /></el-icon>
            {{ form.id ? '保存' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, Reading, Check, Close } from '@element-plus/icons-vue'
import { getScorePage, addScore, updateScore, deleteScore, type StudentScore } from '@/api/score'
import { getAllStudents } from '@/api/student'
import { useUserStore } from '@/store/user'
import type { Student } from '@/types'

const userStore = useUserStore()

// 学生列表（用于下拉选择）
const studentList = ref<Student[]>([])

// 查询表单
const queryForm = reactive({
  current: 1,
  size: 10,
  semester: '',
  courseName: '',
  studentKeyword: ''
})

// 表格数据
const tableData = ref<StudentScore[]>([])
const total = ref(0)
const loading = ref(false)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('录入成绩')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const form = reactive<StudentScore>({
  studentId: 0,
  courseName: '',
  semester: '',
  score: 0,
  credit: 0
})

// 表单验证规则
const rules: FormRules = {
  studentId: [
    { required: true, message: '请输入学生ID', trigger: 'blur' }
  ],
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '课程名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  semester: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入成绩', trigger: 'blur' }
  ],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' }
  ]
}

// 成绩类型
const getScoreType = (score: number) => {
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 60) return 'warning'
  return 'danger'
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    console.log('查询参数:', queryForm)  // 添加日志查看参数
    const data = await getScorePage(queryForm)
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取成绩列表失败', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryForm.current = 1
  getList()
}

// 重置
const handleReset = () => {
  queryForm.semester = ''
  queryForm.courseName = ''
  queryForm.studentKeyword = ''
  handleQuery()
}

// 页码改变
const handleCurrentChange = () => {
  getList()
}

// 每页条数改变
const handleSizeChange = () => {
  queryForm.current = 1
  getList()
}

// 获取学生列表
const getStudentList = async () => {
  try {
    const data = await getAllStudents()
    studentList.value = data
  } catch (error) {
    console.error('获取学生列表失败', error)
  }
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '录入成绩'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: StudentScore) => {
  dialogTitle.value = '编辑成绩'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: StudentScore) => {
  try {
    await ElMessageBox.confirm('确定要删除该成绩记录吗？', '提示', {
      type: 'warning'
    })
    await deleteScore(row.id!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error)
    }
  }
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          await updateScore(form)
          ElMessage.success('更新成功')
        } else {
          await addScore(form)
          ElMessage.success('录入成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    studentId: 0,
    courseName: '',
    semester: '',
    score: 0,
    credit: 0
  })
  delete form.id
}

onMounted(() => {
  getList()
  getStudentList()
})
</script>

<style scoped lang="scss">
.score-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>

